#include <stdio.h>
#include <nvs.h>
#include <nvs_flash.h>

void write_wifi_info(nvs_handle_t nvs_handle, char* ssid, char* password)
{
    printf("Updating wifi info in NVS ... \n");
    esp_err_t err_ssid = nvs_set_str(nvs_handle, "ssid", ssid);
    esp_err_t err = nvs_set_str(nvs_handle, "password", password);
    printf((err_ssid != ESP_OK) ? "SSID Failed!\n" : "SSID Done\n");
    printf((err_ssid != ESP_OK) ? "PASSWORD Failed!\n" : "PASSWORD Done\n");

    // Commit written value.
    // After setting any values, nvs_commit() must be called to ensure changes are written
    // to flash storage. Implementations may write to storage at other times,
    // but this is not guaranteed.
    printf("Committing write wifi info in NVS ... ");
    err = nvs_commit(nvs_handle);
    printf((err != ESP_OK) ? "Failed!\n" : "Done\n");
}

void read_wifi_info(nvs_handle_t nvs_handle)
{
    printf("Reading wifi info from NVS ... ");
    char ssid[100];
    char password[100];
    size_t ssid_length = sizeof(ssid);
    size_t password_length = sizeof(password);

    esp_err_t err_ssid = nvs_get_str(nvs_handle, "ssid", ssid, &ssid_length);
    esp_err_t err_passwd = nvs_get_str(nvs_handle, "password", password, &password_length);

    if (err_ssid == ESP_OK && err_passwd == ESP_OK) {
        printf("Done\n");
        printf("READ NVS WIFI DATA: SSID = %s, PASSWORD = %s\n", ssid, password);
    } else {
        printf("Error (%s) reading!\n", esp_err_to_name(err_ssid));
        printf("Error (%s) reading!\n", esp_err_to_name(err_passwd));


        // write default wifi info
        printf("NVS Write defailt wifi info");
        char *default_ssid = "Codemao-Office";
        char *default_passwd = "2<3]OzU(!h";

        write_wifi_info(nvs_handle, default_ssid, default_passwd);
    }
}